<?php

class Search_MobileController extends Ac_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
        $this->_helper->layout->setLayout('layout-mobile2');
    }
    

    public function indexAction()
    {
        $this->_forward('regular');
    }

    
    public function regularAction()
    {
        $page      = !empty($_GET['page']) ? $_GET['page'] : 1;
        $per_page  = 28;
        
        $res = $this->prepareSearch($page, $per_page);
        extract($res);
        

        if (!empty($_GET['keyword']) && Ac_Util::checkBadWord($_GET['keyword'])) {
            $this->view->disclamer = 1;
        }        
        

       /* 
        $form = $classname::getRefineSearchForm(array('initialize' => false));
        $form->populate($_GET);
        $form->init();
*/

        $form2 = new Search_Form_RegularMobileForm();
        $this->view->form2 = $form2->setAction($this->view->geturl('regular', 'search'))->setMethod('get');

        //load bookmark
        $list_bmk = Model_Bookmark::getList();
        $bookmark = array();
        if (!empty($list_bmk)) {
            foreach($list_bmk as $bmk) {
                if (!empty($bmk->listing)) {
                    $bookmark[] = (string) $bmk->listing->_id;
                }
            }
        }
        $this->view->bookmark = $bookmark;        
        
        $this->view->query = $query;

        $this->view->item_partial   = $classname::getSearchResultPartialName();
        $this->view->sort_by        = $classname::getSearchResultSort();
        $this->view->list           = $list->response->docs;
        $this->view->listing_number = $list->response->numFound;
        $this->view->page           = $page;
        $this->view->per_page       = $per_page;
        /*
        $facet = $list->facet_counts;
        if (isset($facet)) {
            $this->view->facet          = $facet->facet_fields;
        }
         *
         */
        //$this->view->form           = $form->setAction($this->view->geturl('regular', 'search'))->setMethod('get');
        $search = new Model_search();
        $search->url = $_SERVER["REQUEST_URI"];
        $search->get = $_GET;
        $search->user = !empty($this->loggedin_user) ? $this->loggedin_user->_id : '';
        $search->save();

        //get canonical page ready
        $get = $_GET;
        if (empty($get)) {
            $get = array(1 => 1);
        }
        
        if (!Zend_Registry::isRegistered('canonical')) {
            unset($get['page']);
            $this->setCanonical($this->view->geturl('regular', 'search', array('lang' => $this->current_language), null, $get, true));
        }
        
        $this->view->search_id = $search->_id;
        $this->render('result');
    }

    public function getCounterAction()
    {
        $page      = 0;
        $per_page  = 0;
        try {
            $res = $this->prepareSearch($page, $per_page, true);
            extract($res);
            echo (int) $list->response->numFound;
            exit;
        } catch (Exception $e) {
            if (DISPLAY_DEBUG) {
                echo $classname;
                print_r($additionalParameters);
                echo 'error';
            }
        }        
    }

    public function getAttributeAction()
    {
        $class    = $_GET['c'];
        $function = $_GET['f'];

        //Class Cars
        if ($class == 'car' && $function == 'model') {
            $list = Model_Listing_Car::getModel($_GET['id']);
        }
        if ($class == 'car' && $function == 'postad') {
            $list = Model_Listing_Car::getModelPostAd($_GET['id']);
        }
        //Class Motorcycles
        if ($class == 'motorcycle' && $function == 'model') {
            $list = Model_Listing_Motorcycle::getModel($_GET['id']);
        }
        if ($class == 'motorcycle' && $function == 'postad') {
            $list = Model_Listing_Motorcycle::getModelPostAd($_GET['id']);
        }
        //Class Boats : Boat Type/Boat Category
        if ($class == 'boattype' && $function == 'model') {
            $list = Model_Listing_Boat::getBoatCategory($_GET['id']);
        }
        if ($class == 'boattype' && $function == 'postad') {
            $list = Model_Listing_Boat::getBoatCategoryPostAd($_GET['id']);
        }

        //Class Jobs
        if ($class == 'job' && $function == 'model') {
            $list = Model_Listing_Job::getJobFunctionPostAd($_GET['id']);
        }
        if ($class == 'job1' && $function == 'model') {
            $list = Model_Listing_Job::getJobFunction($_GET['id']);
        }
        //Class Location
        if ($class == 'area' && $function == 'area_l2') {
            $list = Model_Location::getAreaL2($_GET['id']);
        }
        //Class Location bis
        if ($class == 'area' && $function == 'area_l2_bis') {
            $list = Model_Location::getAreaL2Search($_GET['id']);
        }
        //Class Location Post Ad
        if ($class == 'area' && $function == 'area_l2_postad') {
            $list = Model_Location::getAreaL2PostAd($_GET['id']);
        }
        $view = $this->view;
        //Class Boats : Make
        if ($class == 'boats' && $function == 'model') {
            $list = Model_Listing_Boat::getBoats($_GET['term']);
            Zend_Controller_Action_HelperBroker::addHelper(
                new ZendX_JQuery_Controller_Action_Helper_AutoComplete()
            );
            
            if ($this->current_language != 'en') {
                foreach($list as $k => $v) {
                    $list[$k] = $view->t($v);
                }
            }
            
            $this->_helper->json($list);
        } else {
            if ($this->current_language != 'en') {
                foreach($list as $k => $v) {
                    $list[$k] = $view->t($v);
                }
            }
            
            $this->_helper->json($list);
        }
    }
    
    private function prepareSearch($page, $per_page, $quiet = false)
    {
        //echo '<pre>';print_r($_GET);exit;

        //var_dump($this->_title);exit;
        $get = $_GET;
        if(empty($get['keyword'])) {
            $get['keyword'] = '';
        } else {
            /*
            $get['keyword'] = str_replace(' ', '+', $get['keyword']).' '.$get['keyword'];
            $get['keyword_boost'] = '"'.str_replace(' ', ' ', $_GET['keyword']).'"^3';
             *
             */
        }

        
        $category = '';
        //print_r($_GET['category_list']);exit;
        $get['category_list'] = empty($get['small_category_list']) ? '' :$get['small_category_list'];
        $main_cat = false;
        if (Zend_Registry::isRegistered('category_list_id')) {
            $id  = Zend_Registry::get('category_list_id');
            $cat = Model_Category::find($id);
            $this->view->category = $cat;
            if (empty($cat->customization)) {
                $get['small_category_list'] = $id;
            }
            else {
                $get['small_category_list'] = $cat->customization;
            }            
            $get['category_list'] = $cat->customization;
            $main_cat = $cat->_id;
            $category = (string) $id;
            $_GET['small_category_list'] = $get['small_category_list'];
        }
        
        if (!empty($_GET['small_category_list'])) {
            $cat = Model_Category::find($_GET['small_category_list']);
            if (!empty($cat)) {
                $category = (string) $cat->_id;
                $main_cat = $cat->_id;
                if (empty($this->view->category)) {
                    //$this->view->category = $cat;
                }
            } elseif (empty($this->view->category)) {
                $cat = Model_Category::one(array('customization' => $_GET['small_category_list'], 'path' => array('$size' => 3)));
                if (!empty($cat) && $parent= $cat->getParent()) {
                    //$category = (string) $cat->_id;
                    $main_cat = $cat->path[0];
                    $this->view->category = $parent;
                }
            }
        }
        
        $solr = Ac_Search::getClient();

        $get['sort'] = !empty($get['sort']) ? $get['sort'] : '';
        $classname = Model_Search::getListingInstance($get['category_list']);
        //print_r($_GET['category_list']);exit;
        //echo $get['keyword'];exit;
        //$listing   = new $classname;
        if (DISPLAY_DEBUG && !$quiet) {
            echo '<pre>';var_dump("classname:$classname<br>");echo '</pre>';
        }
        $classname::processRefineSearchForm($get, $page, $per_page, $query, $fields, $additionalParameters);
        $classname::getFacetedSearch($additionalParameters);
        $title = '';
        if (!empty($main_cat)) {
            //echo 'cas1';
            $cat = Model_Category::find($main_cat);
            
            $main_cat = Model_Category::find($cat->path[0]);
            
            $title = $main_cat->page_title;
            if (empty($title)) {
                $title = $main_cat->name;
            }
            $description = $cat->description;
            if (!empty($description)) {
                $this->view->headMeta()->appendName('description', substr($description, 0, 100));
            }
            if (!empty($main_cat)) {
                $main_cat = $main_cat->_id;
            }
        } elseif (!empty($this->view->category)) {
            //echo 'cas2';
            $main_cat = $this->view->category->path[0];
            $list = $classname::one(array('ca' => $this->view->category->_id));
            $title = $list->category[0]->page_title;
            $this->view->headMeta()->appendName('description', substr($list->category[0]->description, 0, 100));
        } elseif (!empty($_GET['small_category_list'])) {
            //echo 'cas3';
            $main_cat = new MongoId($_GET['small_category_list']);
        }


        if (!empty($_GET['page'])) {
            $title = $this->view->t('page __1__', null, $page) . (!empty($title) ? ' - '.$title : $title);
        }

        if (!empty($_GET['sort'])) {
            $arr = $classname::getSearchResultSort();
            $sort = $this->view->t($arr[$_GET['sort']]);
            $title = ucfirst($sort)  . (!empty($title) ? ' - '.$title : $title);
        }

        if (!empty($title)) {
            $this->addTitle($title);
        }   
        /*
        if (empty($main_cat)) {
            echo 'cas4';
            //$list = $listing::one(array('ca' => array('$size' =>1)));
            //$main_cat = Model_Category::find($list->category[0]->path[0]);
        }
         * 
         */
        //var_dump($main_cat->id);exit;
        if(!empty($main_cat)) {
            Zend_Registry::set('main_category', Model_Category::find($main_cat));
        }
        
        $this->view->sort = !empty($get['sort']) ? $get['sort'] : $additionalParameters['sort'];
        if (empty($additionalParameters['fq'])) {
            $additionalParameters['fq'] = '';
        }

        
        //Only show PUBLISHED Ads
        if (($cat = Model_Category::find(new MongoId($main_cat))) && $cat->id == 'mc52') {
            unset($additionalParameters['qf']);
            $additionalParameters['fq'] .= ' +status:1 +type_obj:'.  Model_Company::TYPE.'  +category:' . $category.' ';
        } else {
            if (empty($additionalParameters['fq'])) {
                $additionalParameters['fq'] .= ' +status:1 +type_obj_s:Model_Listing ';
            }
            else {
                $additionalParameters['fq'] .= ' +status:1 ';
            }
            if (!empty($category)) {
                Zend_Registry::set('current_category', new MongoId($category));
                $additionalParameters['fq'] .= ' +category:' . $category;
            }            
        }
        

        if (DISPLAY_DEBUG && !$quiet) {
            echo '<pre style="clear:both">';
            var_dump($_GET);
            var_dump('Page: '.$page, 'Per_apge: '.$per_page, 'query:'.$query);
            var_dump($additionalParameters);
            if (!empty($additionalParameters['qf'])) {
                print_r($additionalParameters['qf']);
            }
            echo '</pre>';
        }

        if (empty($query)) {
            $query = '*:*';
            $additionalParameters['q.alt'] = $query;
            unset($additionalParameters['defType']);
        }
        $start = ($page-1) * $per_page;
        $list = $solr->search($query, $start, $per_page, $additionalParameters);
        
        
        return array('list' => $list,
                     'query' =>$query,
                     'classname' =>$classname,
        );
    }
}
